package com.mutouren.modules.datapush.web;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.mutouren.common.entity.ResultInfo;
import com.mutouren.common.log.LogAlias;
import com.mutouren.common.log.LogManager;
import com.mutouren.common.log.Logger;
import com.mutouren.common.utils.JsonUtils;

@Controller
@RequestMapping(value = { "/api" }, method = {
		org.springframework.web.bind.annotation.RequestMethod.GET,
		org.springframework.web.bind.annotation.RequestMethod.POST })
public class DemoAction {
	
	private static Logger runLogger = LogManager.getLogger(LogAlias.SystemRun.name());
	private static Logger errorLogger = LogManager.getLogger(LogAlias.SystemError.name());	
	
	@RequestMapping({ "/demo/delay" })
	public void delay(HttpServletRequest request, HttpServletResponse response) throws IOException {
		
		ResultInfo<Object> result = new ResultInfo<Object>();
		String body = "";
		try {
			result.setCode(0);
			result.setMessage("how are you!");
			body = parseBody(request, "utf-8");
						
			String delayTime =request.getParameter("delaytime");
			if (!StringUtils.isBlank(delayTime)){
				Thread.sleep(Integer.parseInt(delayTime));
			} else {
				result.setMessage("not find parameter: delaytime");
			}
			
		} catch(Throwable t) {
			result.setCode(1);
			result.setMessage(t.getMessage());
			errorLogger.error("config error", t);
		} finally {
			writeLog(request, body);	
		}
		
		// 返回
		writeJsonToResponse(response, JsonUtils.beanToJson(result));	
	}
	
	@RequestMapping({ "/demo/hello" })
	public void hello(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String result = "fail";
		String body = "";
		try {
			body = parseBody(request, "utf-8");
						
			result =request.getParameter("helloword");
			if (StringUtils.isBlank(result)){
				result = "not find parameter: helloword";
			}
		} catch(Throwable t) {
			result = t.getMessage();
			errorLogger.error("config error", t);
		} finally {
			writeLog(request, body);	
		}

		// 返回
		writeJsonToResponse(response, result);	
	}	
	
	private static void writeLog(HttpServletRequest request, String content) {
		String url = request.getRequestURL() + "?" + request.getQueryString();
		String ip = request.getRemoteAddr();
		String head = parseHead(request);
		String method = request.getMethod();
		String protocol =  request.getProtocol();
		
		String log = String.format("%s %s %s\r\n%s\r\n%s\r\n%s", protocol, method, url, ip, head, content);
		runLogger.info(log);
	}	
	
	private static String parseHead(HttpServletRequest request) {
		StringBuilder sbResult = new StringBuilder();

		Enumeration<String> headerNames = request.getHeaderNames();
	    while (headerNames.hasMoreElements()) {
	        String key = headerNames.nextElement();
	        String value = request.getHeader(key);
	        sbResult.append(String.format("%s:%s\r\n", key, value));
	    }
	    return sbResult.toString();
	}
	
	private static String parseBody(HttpServletRequest request, String charset) throws IOException {
		StringBuilder sbResult = new StringBuilder();

		BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream(), charset));			
		String line = null;
		while ((line = br.readLine()) != null) {
			if (sbResult.length() != 0) {
				sbResult.append('\n');
			}			
			sbResult.append(line);
		}			
		return sbResult.toString();
	}
	
	private static void writeJsonToResponse(HttpServletResponse response, String jsonText) {
		response.setContentType("application/json;charset=utf-8");
		try {
			response.getOutputStream().write(jsonText.getBytes("utf-8"));
		} catch (Exception e) {
			errorLogger.error("writeJsonToResponse error", e);
		}
	}		
}
